﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using blackhouse.Data;
using mojoPortal.Web.Framework;
using System.Data;

namespace blackhouse.mojoPortalExtend {
    internal class CmsDataAccess : blackhouse.mojoPortalExtend.ICmsDataAccess {

        #region Fields

        private MsSqlAdoDataHelper dataHelper;

        #endregion

        #region Constructors

        public CmsDataAccess() {
            string cs = ConfigHelper.GetStringProperty("MSSQLConnectionString", "");
            this.dataHelper = new MsSqlAdoDataHelper(cs);
            var versioning = new SqlVersionAssembly(cs);
            versioning.UpdateToLatestVersion();
        }

        #endregion

        #region Methods

        public Guid FindPage(string url, int siteId) {
            this.dataHelper.Reset();
            this.dataHelper.ProcedureName = "bhp_FindPage";
            this.dataHelper.AddParameter("Url", url);
            this.dataHelper.AddParameter("SiteId", siteId, DbType.Int32);
            Guid g = Guid.Empty;
            IDataReader reader = this.dataHelper.Execute();
            if (reader.Read())
                g = (Guid)reader["PageGuid"];
            reader.Close();
            return g;
        }

        public Guid FindPageByFunctionality(string functionality, int siteId) {
            this.dataHelper.Reset();
            this.dataHelper.ProcedureName = "bhp_FindPageByFunctionality";
            this.dataHelper.AddParameter("Function", functionality);
            this.dataHelper.AddParameter("SiteId", siteId, DbType.Int32);
            Guid g = Guid.Empty;
            IDataReader reader = this.dataHelper.Execute();
            if (reader.Read())
                g = (Guid)reader["PageGuid"];
            reader.Close();
            return g;
        }

        public void SetCmsPageByFunctionality(string functionality, int pageId) {
            this.dataHelper.Reset();
            this.dataHelper.ProcedureName = "bhp_SetPageByFunctionality";
            this.dataHelper.AddParameter("Function", functionality);
            this.dataHelper.AddParameter("PageId", pageId, DbType.Int32);
            this.dataHelper.ExecuteWithoutResult();
        }

        public int FindUrlByFunctionality(string functionality, int siteId) {
            this.dataHelper.Reset();
            this.dataHelper.ProcedureName = "bhp_FindUrlByFunctionality";
            this.dataHelper.AddParameter("Function", functionality);
            this.dataHelper.AddParameter("SiteId", siteId, DbType.Int32);
            IDataReader reader = this.dataHelper.Execute();
            int urlId = 0;
            if (reader.Read())
                urlId = Convert.ToInt32(reader[0]);
            reader.Close();
            return urlId;
        }

        #endregion

    }
}
